<?php

namespace app\admin\controller\shopro;

use app\admin\model\shopro\Bonus;
use app\admin\model\shopro\BonusLog as BonusLogModel;
use app\admin\model\shopro\Pclog as PclogModel;

/**
 * 奖金池
 */
class BonusLog extends Common
{

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new BonusLogModel();
    }



    /**
     * 列表
     */
    public function index()
    {
        $money=Bonus::find()["money"]??0;
        if (!$this->request->isAjax()) {
            $exportConfig = (new \addons\shopro\library\Export())->getConfig();
            $this->assignconfig("save_type", $exportConfig['save_type'] ?? 'download');
            $this->assign("money",$money);
            return $this->view->fetch();
        }
        $where=[];
        if($this->request->param("search")){
            $search=json_decode($this->request->param("search"),true);
            if(isset($search["user_id"])) $where["user_id"]=["=",$search["user_id"][0]];
            if(isset($search["user.nickname"])) $where["user_info.nickname"]=["like", '%'.$search["user.nickname"][0].'%'];
            if(isset($search["user.mobile"])) $where["user_info.mobile"]=["like",'%'.$search["user.mobile"][0].'%'];
        }
        $log = $this->model
            ->alias("bonus_log")
            ->field("bonus_log.*")
            ->with(['user'])
            ->join("user user_info","user_info.id=bonus_log.user_id","left")
            ->where($where)
            ->order("createtime desc,id desc")
            ->paginate($this->request->param('list_rows', 10));
        $data["data"]=$log;
        $data["money"]=$money;
        $this->success('获取成功', null, $data);
    }
    /**
     * 详情
     *
     * @param  $id
     */
    public function detail($id)
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }
        $detail = $this->model->with("user")->find($id);
        if (!$detail) {
            $this->error(__('No Results were found'));
        }
        $detail["createtime"]=date("Y-m-d H:i:s",$detail["createtime"]);
        $detail["order_details"]=json_decode($detail["order_details"],true);
        $this->success('详情', null, $detail);
    }


    /**
     * 导出
     * */
    public function export()
    {
        $cellTitles = [
            'id' => 'ID',
            'user.id' => '用户ID',
            'user.nickname' => '用户昵称',
            'user.mobile' => '用户手机号码',
            'money' => '金额',
            'order_pv' => '订单pv值/分红池金额',
            'momo' => '备注',
            'ratio' => '比例',
            'createtime' => '创建时间',
        ];

        // 数据总条数
        $where=[];
        if($this->request->param("search")){
            $search=json_decode($this->request->param("search"),true);
            if(isset($search["user_id"])) $where["user_id"]=["=",$search["user_id"][0]];
            if(isset($search["user.nickname"])) $where["user_info.nickname"]=["like", '%'.$search["user.nickname"][0].'%'];
            if(isset($search["user.mobile"])) $where["user_info.mobile"]=["like",'%'.$search["user.mobile"][0].'%'];
        }
        $total = $this->model
            ->alias("bonus_log")
            ->field("bonus_log.*")
            ->with(['user'])
            ->join("user user_info","user_info.id=bonus_log.user_id","left")
            ->where($where)
            ->order("bonus_log.createtime desc,bonus_log.id desc")->count();
        if ($total <= 0) {
            $this->error('导出数据为空');
        }
        $export = new \addons\shopro\library\Export();
        $params = [
            'file_name' => '奖金池明细列表',
            'cell_titles' => $cellTitles,
            'total' => $total,
            'is_sub_cell' => false,
        ];

        $result = $export->export($params, function ($pages) use ($where, $total) {
            $datas =$this->model
                ->alias("bonus_log")
                ->field("bonus_log.*")
                ->with(['user'])
                ->join("user user_info","user_info.id=bonus_log.user_id","left")
                ->where($where)
                ->order("bonus_log.createtime desc,bonus_log.id desc")
                ->limit((($pages['page'] - 1) * $pages['list_rows']), $pages['list_rows'])
                ->select();
            $datas = collection($datas);
            $newDatas = [];
            foreach ($datas as &$item) {
                $data = [
                    // 订单表字段
                    'id' => $item['id'],
                    'user.id' =>$item["user"]["id"]??0,
                    'user.nickname' =>$item["user"]["nickname"]??'',
                    'user.mobile' =>"@".$item["user"]["mobile"]??'',
                    'money' =>$item["money"],
                    'order_pv' =>$item["order_pv"],
                    'momo' =>$item["momo"],
                    'ratio' =>$item["ratio"],
                    'createtime' =>date("Y-m-d H:i:s",$item["createtime"]),
                ];
                $newDatas[] = $data;
            }
            if ($pages['is_last_page']) {
                $money=Bonus::find()["money"]??0;
                $newDatas[] = ['order_id' => "当前奖金池金额：" . $money];
            }
            return $newDatas;
        });

        $this->success('导出成功' . (isset($result['file_path']) && $result['file_path'] ? '，请在服务器: “' . $result['file_path'] . '” 查看' : ''), null, $result);
    }
}
